class Solution {
public:
    void dfs(int i, int size, vector<vector<int>>& ans, vector<int>& path,
             vector<int>& nums) {
        if (i == nums.size()) {
            vector<int> cur;
            for (int j = 0; j < size; j++) {
                cur.emplace_back(path[j]);
            }
            ans.emplace_back(cur);
        } else {
            int j = i + 1;
            while (j < nums.size() && nums[i] == nums[j]) {
                j++;
            }
            dfs(j, size, ans, path, nums);
            for (; i < j; i++) {
                path[size++] = nums[i];
                dfs(j, size, ans, path, nums);
            }
        }
    }
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        vector<vector<int>> ans;
        vector<int> path(n);
        dfs(0, 0, ans, path, nums);
        return ans;
    }
};